#!/bin/bash
#Zabbix安装脚本
##定义字体效果
#红色背景
red_bg='\e[41;33;1m'
#红色字体
red_zt='\e[1;31m'
#绿色背景
green_bg='\033[0;32;1m'
#绿色字体
green_zt='\e[1;32m'
#关闭效果
end='\033[0m'
#字体闪烁
ss='\033[05m'
#消隐
sy='\33[08m'
##常用语句定义区
print_green_bg_red_zt(){
	echo -e "${green_bg}${ss}${green_bg}正在进入...${end}${end}${end}\n${red_zt}${1}...${end}"
}
print_red_z_green_z_info(){
	echo -e "${red_zt}${1}:${end}${green_zt}${2}${end}"
}
cheks(){
	echo -e "${red_zt}正在检测${1}...${end}"
}
print_green_zt(){
	echo -e "${green_zt}${1}${end}"
}
print_red_z_green_z(){
	echo -e "${red_zt}${1}${end}${green_zt}${2}${end}${green_zt}${3}${end}"
}
print_red_z(){
	echo -e "${red_zt}${1}${end}"
}
print_red_z_b(){
	echo -e "${red_bg}${1}${end}"
}
print_red_z_z_bg(){
	echo -e "${red_zt}${1}${end}${red_bg}${2}${end}"
}
input(){
	echo -e "${red_zt}${1}${end}"
	read $2
}
install_check(){
    print_red_z_green_z_info "安装配置信息确认"
    input "当前主机名预配置为: $HOST_NAME\n按回车继续安装" "dd"
}
chek_status(){
    if [[ "$1" -eq '0' ]];then
        print_red_z_green_z_info "$2" "成功"
        return 0
    else
        status='true'
        while $status;do
            print_red_z_z_bg "$2" "失败"
            err='n'
            input "是否停止脚本运行[当前脚本PID: $$]\n输入f忽略该提示" "err"
            if [[ "$err" == 'f' ]];then
                status='false'
                if [[ "$status" == 'false' ]];then
                    print_red_z "已跳过该错误:[${2}失败]"
                else
                    status='true'
                fi
            else
                status=true
            fi
        done
    fi
}
#服务循环安装
if [[ "$display" == 'y' || "$display" == 'Y' ]];then
    export install_s='yum install -y'
    export unstall_s='yum remove -y '
else
    export install_s='yum install -y -q'
    export unstall_s='yum remove -y -q'
fi
service_install(){
    for i in $*;do
        print_red_z_green_z_info "正在安装---->>>>" "${i}\t安装速度根据包的大小及网络而定,请耐心等待"
        print_red_z_green_z_info "当前脚本进程PID---->>>" "$$"
        $install_s $i
        chek_status "$?" "${i}安装"
    done
}
#服务卸载
service_unstall(){
    input "即将卸载以下服务:\n$* \n是否全部卸载[y/n]" "re"
    for i in $*;do
        print_green_zt "$i"
    done
    if [[ "$re" == "y" || "$re" == "Y" ]];then
        for i in $*;do
            print_red_z_green_z_info "正在卸载---->>>>" "$i"
            $unstall_s $i
            chek_status "$?" "${i}卸载"
        done
    else
        input "是否自定义输入卸载[y/n]" "zre"
        if  [[ "$zre" == "y" || "$zre" == "Y" ]];then
            input "请输入需要卸载的包,并以空格分开" "sre"
            for i in $sre;do
                $unstall_s $i
            done
        else
            print_red_z "跳过卸载"
        fi
    fi
}
#服务启动
service_start(){
    systemctl daemon-reload
    for i in $*;do
        systemctl restart $i
        chek_status "$?" "${i}服务启动"
        systemctl enable $i > /dev/null
        chek_status "$?" "${i}设置服务开机启动"
    done
}
service_stop(){
    for i in $*;do
        systemctl stop $i
        chek_status "$?" "${i}服务关闭"
        systemctl disable $i > /dev/null
        chek_status "$?" "${i}关闭开机启动"
    done
}
service_chek(){
    print_red_z_green_z_info "正在检查" "$1"
    ser=`$local_search | grep $1`
    if [[ -n "$ser" ]];then
        input "检测到本机已安装[$1]相关服务,请选择一个操作\n[1]跳过此服务[默认选项]\n[2]卸载该服务" db_remove
        if [[ "$db_remove" == '2' ]];then
            service=`$local_search | grep $1`
            service_unstall "$service"
        else
            print_red_z_green_z_info "跳过卸载" "$service"
            db_init='y'
        fi
    fi
}
cmd(){
    for i in $*;do
        print_red_z_green_z_info "正在执行" "$i"
        $i
        chek_status "$1" "执行"
    done
}
mysql_cmd(){
    cmd="$1"
    print_red_z_green_z "正在执行数据库语句:" "[ $cmd ]"
    mysql -uroot -p$r_p -e "$cmd"
    if [[ "$?" -eq '0' ]];then
        return 0
    else
        return 404
    fi
}
if [[ "$USER" -eq 'ROOT' ]];then
    print_green_zt "正在使用${USER}用户"
else
    print_red_z_b "请使用root用户"
    exit 1
fi
init_mariadb(){
    mysql -e "show databases;" > /dev/null
    if [[ "$?" -eq "0" ]];then
        mysql -e "use mysql;UPDATE mysql.user SET authentication_string = PASSWORD('$r_p'), plugin = 'mysql_native_password' WHERE User = 'root' AND Host = 'localhost';FLUSH PRIVILEGES;"
        chek_status "$?" "初始化数据库 [ root ]用户密码"
    else
        mysql_cmd "show databases;"
        chek_status "$?" "初始化数据库 [ root ]用户密码"
    fi
}
mariadbs(){
    print_red_z_green_z "开始配置" "数据库服务"
    service_start "mariadb"
    ##初始化数据库
    init_mariadb    
    chek_status "$?" "数据库初始化"
    mysql_cmd "drop database test;"
    chek_status "$?" "删除测试数据库"
    mysql_cmd "create database ${z_d} character set utf8 collate utf8_bin;"
    chek_status "$?" "创建数据库:${z_d}"
    mysql_cmd "GRANT ALL PRIVILEGES ON ${z_d}.* TO '${z_u}'@'localhost' IDENTIFIED BY '${z_p}';flush privileges;"
    chek_status "$?" "设置[ $z_u ]用户[ localhost ]登录权限"
    mysql_cmd "GRANT ALL PRIVILEGES ON ${z_d}.* TO '${z_u}'@'%' IDENTIFIED BY '${z_p}';flush privileges;"
    chek_status "$?" "设置[ $z_u ]用户[ % ]登录权限"
    mysql_cmd "GRANT ALL PRIVILEGES ON ${z_d}.* TO '${z_u}'@'${z_host}' IDENTIFIED BY '${z_p}';flush privileges;"
    chek_status "$?" "设置[ $z_u ]用户[ $z_host ]登录权限"
}
zabbix_config(){
    sed -i  's/# php_value.*/php_value date.timezone Asia\/Shanghai/' /etc/httpd/conf.d/zabbix.conf
    cp /etc/zabbix/zabbix_server.conf /etc/zabbix/zabbix_server.conf.bak #备份
echo -e "LogFile=/var/log/zabbix/zabbix_server.log
LogFileSize=0
PidFile=/var/run/zabbix/zabbix_server.pid
SocketDir=/var/run/zabbix
DBHost=$z_ip
DBName=$z_d
DBUser=$z_u
DBPassword=$z_p
SNMPTrapperFile=/var/log/snmptrap/snmptrap.log
Timeout=4
AlertScriptsPath=/usr/lib/zabbix/alertscripts
ExternalScripts=/usr/lib/zabbix/externalscripts
LogSlowQueries=3000" > /etc/zabbix/zabbix_server.conf
    srv="zabbix-server.service zabbix-agent.service httpd"
    service_start "$srv"
}
init_zabbix_db(){
    create_file=`rpm -ql zabbix-server-mysql | grep create.sql.gz`
    if [[ -f "$create_file" ]];then
        print_red_z_green_z "正在初始化数据库[ $z_d ]" "请耐心等待"
        zcat $create_file | mysql -u${z_u} -p${z_p} ${z_d}
        chek_status "$?" "初始化数据库 [ $z_d ]"
    else
        print_red_z "找不到文件 [ $create_file ]\n请自行初始化zabbix数据库服务"
        exit 11
    fi
}
Zabbix_source(){
echo -e '
[zabbix]
name=Zabbix Official Repository - $basearch
baseurl=http://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/4.0/rhel/7/$basearch/
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591
 
[zabbix-debuginfo]
name=Zabbix Official Repository debuginfo - $basearch
baseurl=http://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/4.0/rhel/7/$basearch/debuginfo/
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591
gpgcheck=0
 
[zabbix-non-supported]
name=Zabbix Official Repository non-supported - $basearch
baseurl=http://mirrors.tuna.tsinghua.edu.cn/zabbix/non-supported/rhel/7/$basearch/
enabled=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX
gpgcheck=0' > /etc/yum.repos.d/Zabbix.repo
}
sources(){
    print_green_zt "开始配置源"
    if [[ ! -d '/yum/' ]];then
        mkdir -p /yum/
        mv /etc/yum.repos.d/* /yum/
    fi
    rm -f /etc/yum.repos.d/*
    Zabbix_source
    if [[ "$1" == "7" ]];then
         curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo > /dev/null
         cheks "系统源下载"
    elif [[ "$1" == "8" ]];then
        curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-8.repo > /dev/null
        cheks "系统源下载"
        sed -i 's/7/8/g' /etc/yum.repos.d/Zabbix.repo
    else
         curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo > /dev/null
         cheks "系统源下载"
    fi
    sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
    print_green_zt "正在验证源"
    yum clean all > /dev/null
    cheks "清除源缓存"
    yum makecache > /dev/null
    cheks "建立源索引"
}
os_config(){
    print_green_zt "开始配置系统环境"
    service_stop "firewalld"
    sed -i 's/SELINUX=.*/SELINUX=disabled/g' /etc/sysconfig/selinux /etc/selinux/config
    setenforce 0
}
installs(){
    print_green_zt "开始安装服务........"
    svc="ntpdate mariadb-server zabbix-server-mysql zabbix-web-mysql  zabbix-agent httpd expect  MySQL-python mariadb"
    service_install "$svc"
    ntpdate time.windows.com > /dev/null
    cheks "第一次网络时间同步"
    ntpdate time.windows.com > /dev/null
    cheks "第二次网络时间同步"
    systemctl enable mariadb  zabbix-server httpd > /dev/null
    cheks "设置服务开机自启"
}
info_chek(){
    if [[ -z "$1" ]];then
        print_red_z_b "${2}未设置"
        input "按回车使用默认参数" Y
        if [[ "$2" == "数据库管理员密码" ]];then
            r_p='The_is_root_passwd1?'
        elif [[ "$2" == "zabbix数据库用户名" ]];then
            z_u='zabbix'
        elif [[ "$2" == "zabbix数据库用户密码" ]];then
            z_p='The_is_zabbix_passwd1?'
        elif [[  "$2" == "zabbix数据库名" ]];then
             z_d='zabbix'
        elif [[  "$2" == "该服务器IP地址:" ]];then
            z_ip=`hostname -I | awk '{print $1}'`
        elif [[  "$2" == "服务器主机名:" ]];then
            z_host='zabbix-server'
        fi
    fi
}
infos(){
    print_red_z "安装信息配置:"
    print_red_z_green_z "数据库[ ROOT ]用户密码:" "[ ${r_p} ]"
    print_red_z_green_z "数据库 [ zabbix ]名称:" "[ ${z_d} ]"
    print_red_z_green_z "[ zabbix ]数据库库用户名:" "[ ${z_u} ]"
    print_red_z_green_z "[ ${z_u} ]数据库用户密码:" "[ ${z_p} ]"
    print_red_z_green_z "服务器[ IP ]地址:" "[ ${z_ip} ]"
    print_red_z_green_z "服务器主机名:" "[ ${z_host} ]"
}
os_ver=`awk -F= '/^NAME/{print $2}' /etc/os-release | sed 's/"//g'| awk '{print $1}'`
if [[ ! -f '/etc/os-release' ]];then
    print_red_z_b "当前系统非Linux"
else
    os_ver=`awk -F= '/^NAME/{print $2}' /etc/os-release | sed 's/"//g'| awk '{print $1}'`
    if [[ "$os_ver" == "CentOS" ]];then
        s=`awk '{print $4}' /etc/redhat-release | cut -b 1`
        if [[ "$s" == "7" || "$s" == "8" ]];then
            print_green_zt "此脚本已适配当前系统"
            input "是否自定义数据库密码[ y/n ],默认[ n ]" "db"
            if [[ "$db" == "y" ]];then
                input "请输入数据库管理员[ root ]密码:" "r_p"
                input "请输入 [ zabbix ] 数据库用户名:" "z_u"
                input "请输入[ $z_u ]用户密码" "z_p"
                input "请输入[ zabbix ]数据库名称" "z_d"
                input "请输入该服务器IP地址:" "z_ip"
                input "请输入该服务器主机名:" "z_host"
                info_chek "${r_p}" "数据库管理员密码"
                info_chek "${z_u}" "zabbix数据库用户名"
                info_chek "${z_p}" "zabbix数据库用户密码"
                info_chek "${z_d}" "zabbix数据库名"
                info_chek "${z_ip}" "该服务器IP地址:"
                info_chek "${z_host}" "服务器主机名:"
            else
                r_p='The_is_root_passwd1?'
                z_u='zabbix'
                z_p='The_is_zabbix_passwd1?'
                z_d='zabbix'
                z_ip=`hostname -I | awk '{print $1}'`
                z_host='zabbix-server'
            fi
            infos
            input "按回车继续" "Y"
            hostnamectl set-hostname ${z_host}
            echo -e "${z_ip} ${z_host}" >> /etc/hosts
            os_config
            cheks "系统配置"
            sources "$s"
            cheks "源配置"
            installs
            cheks "全部服务安装"
            mariadbs
            cheks "数据库初始化配置"
            zabbix_config
            cheks "Zabbix服务配置"
            init_zabbix_db
            cheks "zabbix数据库环境初始化"
        else
            print_red_z_b "仅支持CentOS7和CentOS8"
            exit 78
        fi
    else
        print_red_z_b "当前系统暂未适配,是否终止[y/n],默认[y]" "error"
    fi
fi
infos
print_red_z_green_z "请在浏览器输入下面的网址:"  "http://${z_ip}/zabbix"
print_red_z "Zabbix用户名密码信息如下:"
print_red_z_green_z "登录用户名:" "Admin"
print_red_z_green_z "登录密码:" "zabbix"